<?php

namespace App\Http\Controllers;

use DB;
use Illuminate\Http\Request;
use Validator;

use Ptime3\Functions\JoinData;
use Ptime3\Functions\Queue;

class TeamController extends Controller
{

    public function index(Request $request){
        $input = $request->all();
        //参数检验
        $validator = Validator::make($input,
            [
                'search'  => 'string|min:1',
                'page'	  => 'integer|min:1',
                'user_id' => 'integer|min:1'
            ]
        );
        if($validator->fails()){
            return $this::jsonResponse(true,$validator->messages(),"paramError");
        }

        $userId = !empty($input["user_id"])?$input["user_id"]:0;
        
        $search       = !empty($input["search"])?$input["search"]:"";
        $countPerPage = 20;
        $countSkip    = !empty($input["page"])?$countPerPage*($input["page"]-1):0;

        $teamResult = DB::select("SELECT tm_team.id,tm_team.name,tm_team.description,tm_team.icon,
                tm_team.leader_id,tm_team.is_verified,tm_team.is_public,tm_team.created_at,tm_team.user_count,
                tm_team_user.state FROM tm_team 
                LEFT JOIN tm_team_user ON tm_team_user.team_id = tm_team.id AND tm_team_user.user_id = $userId AND tm_team_user.is_deleted = 0
                WHERE tm_team.is_public = 1 AND tm_team.is_deleted = 0 AND tm_team.name LIKE '%$search%'
                ORDER BY tm_team.user_count DESC LIMIT $countSkip,$countPerPage 
                ");

        foreach ($teamResult as $key => $value) {
            $value->state = $value->state == null ? -1 : $value->state;
        }

        $teamResult = JoinData::user($teamResult,"leader");

        return $this->jsonResponse(false,$teamResult);
    }

    public function show(Request $request, $teamId){
        $input = $request->all();
        //参数检验
        $validator = Validator::make($input,
            [
                'user_id' => 'integer|min:1'
            ]
        );
        if($validator->fails())
            return $this::jsonResponse(true,$validator->messages(),"paramError");

        if(strlen($teamId) == 6 && !is_numeric($teamId)){
            $teamId = DB::table("tm_team")->where("invite_code",$teamId)->pluck("id");
            if(empty($teamId))
                return $this->jsonResponse(true,[],"邀请码失效！");
        }

        $teamResult = DB::table("tm_team")
            ->select("tm_team.id","tm_team.name","tm_team.leader_id","tm_team.is_public","tm_team.is_verified",
                "tm_team.description","tm_team.icon","tm_team.created_at")
            ->where("tm_team.id",$teamId)->where("tm_team.is_deleted",false)
            ->first();

        if(isset($input["user_id"])){
            $teamResult->is_stick = DB::table("tm_team_user")
                ->where("user_id",$input["user_id"])
                ->where("team_id",$teamId)
                ->where("state",1)
                ->where("is_deleted",false)
                ->value("is_stick");
        }

        $teamResult = JoinData::user([$teamResult],"leader")[0];

        return $this->jsonResponse(false,$teamResult);
    }   

    public function store(Request $request){
        $input = $request->all();
        //参数检验
        $validator = Validator::make($input,
            [
                'name'        => 'required|string|min:2',
                'leader_id'   => 'required|integer|min:1',
                'is_public'	  => 'boolean',
                'description' => 'string|min:5',
                'icon'        => 'string|min:1',
                'source_name' => 'string|min:2',
                'source_id'   => 'string|min:1',
            ]
        );
        if($validator->fails())
            return $this::jsonResponse(true,$validator->messages(),"paramError");

        $icon     = empty($input["icon"])?"/uploads/default/team".rand(1,4).".png":$input["icon"];
        $name     = $input["name"];
        $leaderId = $input["leader_id"];

        //创建团队
        $inviteCode = strtoupper(str_random(6));
        $teamData = [
        	"name" 		 => $name,
        	"leader_id"  => $leaderId,
        	"is_public"  => empty($input["is_public"])?0:1,
        	"description"=> isset($input["description"])?$input["description"]:"",
        	"icon"		 => $icon,
            "source_name"=> isset($input["source_name"])?$input["source_name"]:"",
            "source_id"  => isset($input["source_id"])?$input["source_id"]:"",
        	"invite_code"=> $inviteCode
        ];
        $teamId = DB::table("tm_team")->insertGetId($teamData);

        $teamUserData = [
        	"team_id"  => $teamId,
        	"user_id"  => $leaderId,
        	"state"    => 1,
        	"join_time"=> date("Y-m-d H:i:s")
        ];
        
        DB::table("tm_team_user")->insert($teamUserData);

        //创建通知集
        $setData = [
            "app_id"    => env("TEAM_APP_ID"),
            "name"      => $name,
            "icon"      => $icon,
            "object"    => "team",
            "object_id" => $teamId
        ];
        Queue::put("restapi",["post","inform","im_set",$setData]);

        //发送欢迎通知
        $urlPage    = json_encode([
            "page"      => "team.invite",
            "params"    =>[
                "team_id" => $teamId
            ]
        ]);
        $informData = [
            "title"     => "恭喜你成功创建团队 ".$name,
            "app_id"    => env("TEAM_APP_ID"),
            "object"    => "team",
            "object_id" => $teamId,
            "sender_id" => $leaderId,
            "users"     =>[["user_id"=>$leaderId]],
            "is_notcare"=>true,
            "reply_opts"=>[["content"=>"去召集小伙伴","is_expected"=>true,"url_page"=>$urlPage],["content"=>"好的"]]
        ];
        Queue::put("restapi",["post","inform","inform/send",$informData]);

        return $this->jsonResponse(false,$teamId);
    }

    public function update(Request $request, $teamId){
        $input = $request->all();
        //参数检验
        $validator = Validator::make($input,
            [
                'name'        => 'string|min:2',
                'is_public'   => 'boolean',
                'description' => 'string|min:5',
                'icon'        => 'string|min:1',
            ]
        );
        if($validator->fails())
            return $this::jsonResponse(true,$validator->messages(),"paramError");

        //更新团队
        $teamData = [];
        foreach (["name","is_public","description","icon"] as $value) {
             if(isset($input[$value]))  $teamData[$value] = $input[$value];
        }
        
        if(empty($teamData))
            return $this->jsonResponse(true,[],"无更新数据！");

        $teamUpdateResult = DB::table("tm_team")
            ->where("id",$teamId)->where("is_deleted",false)->update($teamData);

        //更新通知集
        if(isset($input["name"]) || isset($input["icon"])){
            $setData = [
                "app_id"    => env("TEAM_APP_ID"),
                "object"    => "team",
                "object_id" => $teamId
            ];
            $setData = [];
            foreach (["name","icon"] as $value) {
                 if(isset($input[$value]))  $setData[$value] = $input[$value];
            }
            Queue::put("restapi",["put","inform","im_set",$setData]);
        }
        return $this->jsonResponse(false,$teamUpdateResult);
    }

    public function destroy($teamId){
        $teamUserResult = DB::table("tm_team_user")->select("user_id")
            ->where("team_id",$teamId)->where("state",1)->where("is_deleted",false)->get();
        $informUsers = [];
        foreach ($teamUserResult as $key => $value) {
            $informUsers[] = ["user_id"=>$value->user_id];
        }

        //解散
        $teamDestroyResult = DB::table("tm_team")->where("id",$teamId)->update(["is_deleted"=>true]);
        DB::table("tm_team_user")->where("team_id",$teamId)->update(["is_deleted"=>true]);

        //删除通知集
        $setData = [
            "app_id"    => env("TEAM_APP_ID"),
            "object"    => "team",
            "object_id" => $teamId
        ];
        Queue::put("restapi",["deleted","inform","im_set",$setData]);

        //发送解散通知
        if($teamDestroyResult){
            $appId       = env("TEAM_APP_ID");
            $appSetId    = env("TEAM_SET_ID");
            $appSenderId = env("TEAM_SENDER_ID");

            $teamName  = DB::table("tm_team")->where("id",$teamId)->value("name");
            $informData = [
                "title" 	=> "$teamName 已被解散",
                "app_id"    => $appId,
                "set_id" 	=> $appSetId,
                "sender_id" => $appSenderId,
                "users"		=> $informUsers,
                "methods"   =>[["method_id"=>1]],
                "reply_opts"=>[["content"=>"好的"]],
                "is_notcare"=>true
            ];
            Queue::put("restapi",["post","inform","inform/send",$informData]);
        }

        return $this->jsonResponse(false,$teamDestroyResult);
    }

    public function inviteCodeShow($teamId){
        $inviteCode = DB::table("tm_team")->where("id",$teamId)->value("invite_code");
        return $this->jsonResponse(false,$inviteCode);
    }

    public function inviteCodeRefresh($teamId){
        $inviteCode = strtoupper(str_random(6));
        $teamResult = DB::table("tm_team")->where("id",$teamId)->update(["invite_code"=>$inviteCode]);
        return $this->jsonResponse(false,$inviteCode);
    }
}
